<template>
  <admin-container title="文章编辑" class="artcie-form-container">
    <div class="form">
      <el-form :model="form" ref="form" :rules="rules" size="small" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" maxlength="100" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="Ttile" prop="titleEn">
          <el-input v-model="form.titleEn" placeholder="Please enter the title of the article" maxlength="255"
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="封面图">
          <div class="cover-drawing">
            <div>
              <el-upload :before-upload="upload" accept="image/jpeg,image/jpg,image/png" action="#" :limit="1">
                <el-button size="small" type="primary">图片上传</el-button>
                <span class="reminder">* 推荐使用尺寸 400 * 240, 文件大小不能超过2mb</span>
              </el-upload>
            </div>
            <div>
              <div class="upload-box-img">
                <img v-if="form.coverUrl != null && form.coverUrl != ''" :src="form.coverUrl">
              </div>
            </div>
            <div>
              <p class="reminder">* 如不上传封面图，默认从内容中提取第一张图片作为封面图</p>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div style="border: 1px solid #ccc;">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="form.content" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="onCreated" />
          </div>
        </el-form-item>
        <el-form-item label="Content">
          <div style="border: 1px solid #ccc;">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorEn" :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="form.contentEn" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="onCreatedEn" />
          </div>
        </el-form-item>
        <el-form-item label="发布设置">
          <div class="form-set">
            <div class="form-set-item">
              <label>文章类目</label>
              <el-select style="width: 100px;" v-model="form.category" placeholder="请选择文章类目">
                <el-option label="公司新闻" :value="1"></el-option>
                <el-option label="行业新闻" :value="2"></el-option>
              </el-select>
            </div>
            <div class="form-set-item">
              <label>立刻发布</label>
              <el-switch v-model="form.display">
              </el-switch>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div class="fix-buttons">
        <div class="button-group">
          <template v-if="form.id != 0">
            <el-button size="small" type="primary" @click="update"><i class="el-icon-check"></i> 修改保存</el-button>
            <el-button size="small" type="danger" @click="handleDelete"><i class="el-icon-delete"></i> 删除文章</el-button>
          </template>
          <template v-else>
            <el-button size="small" type="primary" @click="submit"><i class="el-icon-check"></i> 提交保存</el-button>
          </template>
        </div>
      </div>
    </div>
  </admin-container>
</template>

<script>
import AdminContainer from '@/components/Admin/AdminContainer.vue';
import * as articleApi from '@/api/admin/articleApi';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css';
import * as storage from '@/utils/localStorageUtil';

export default {
  components: {
    AdminContainer,
    Editor,
    Toolbar
  },
  data () {
    var self = this;
    return {
      form: {
        id: 0,
        title: '',
        category: 1,
        content: '',
        coverUrl: '',
        display: true,
        titleEn: '',
        contentEn: '',
        brief: '',
        briefEN: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
        ],
        titleEn: [
          { required: true, message: 'Please enter the title of the article', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入文章', trigger: 'blur' },
        ]
      },
      editor: null,
      editorEn: null,
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadVideo: {
            server: process.env.API_ROOT + '/api/admin/Article/UploadMedia',
            fieldName: "mediaFile",
            maxNumberOfFiles: 1,
            headers: {
              Authorization: storage.getLocalStorage('francis:jwt')
            },
            onError: function (xhr, err) {
              self.$message.error(err.message);
            },
          },
          uploadImage: {
            server: process.env.API_ROOT + '/api/admin/Article/UploadMedia',
            fieldName: 'mediaFile',
            maxNumberOfFiles: 1,
            headers: {
              Authorization: storage.getLocalStorage('francis:jwt')
            },
            onError: function (xhr, err) {
              if (err.message.indexOf('exceeds') > -1) {
                self.$message.error('上传的图片大小不能大于2mb');
              }
              else {
                self.$message.error(err.message);
              }
            },
          }
        },
      },
      mode: 'default',
    }
  },
  watch: {
    'form.content' (newVal, oldVal) {
      var self = this;
      if (self.form.coverUrl == null || self.form.coverUrl == '') {
        //获取editor中第一张图片的URL
        let reg = /<img.*?src="(.*?)"/;
        let match = this.form.content.match(reg);
        let firstImageUrl = match ? match[1] : '';
        self.form.coverUrl = firstImageUrl;
      }
    },
    'form.contentEn' (newVal, oldVal) {
      var self = this;
      if (self.form.coverUrl == null || self.form.coverUrl == '') {
        //获取editor中第一张图片的URL
        let reg = /<img.*?src="(.*?)"/;
        let match = this.form.contentEn.match(reg);
        let firstImageUrl = match ? match[1] : '';
        self.form.coverUrl = firstImageUrl;
      }
    },
  },
  methods: {
    upload (file) {
      var self = this;
      if (file.type.includes('image/') && file.size > 2 * 1024 * 1024) {
        self.$message.error('上传的图片大小不能大于2mb');
        return false;
      }
      const formData = new FormData();
      formData.append("mediaFile", file);
      articleApi.uploadMedia(formData)
        .then(res => {
          if (res.errno == 0) {
            self.form.coverUrl = res.data.url;
          }
          else {
            self.$message.error(res.message);
          }
        })
        .catch(err => {
          self.$message.error('上传发生错误，请重新尝试');
        })
      return false;
    },
    onCreated (editor) {
      this.editor = Object.seal(editor);
    },
    onCreatedEn (editor) {
      this.editorEn = Object.seal(editor);
    },
    submit () {
      var self = this;
      self.$refs.form.validate(valid => {
        if (valid) {
          if (self.form.coverUrl == null || self.form.coverUrl == '') {
            //获取editor中第一张图片的URL
            let reg = /<img.*?src="(.*?)"/;
            let match = this.form.content.match(reg);
            let firstImageUrl = match ? match[1] : '';
            self.form.coverUrl = firstImageUrl;
          }
          var text = this.editor.getText();
          var textEn = this.editorEn.getText();
          self.form.brief = text.length >= 100 ? this.editor.getText().substring(0, 100) : text;//中文只截取100个字
          self.form.briefEN = textEn.length >= 200 ? this.editorEn.getText().substring(0, 200) : textEn;//英文只截取200个字

          articleApi.addArticle(self.form)
            .then(res => {
              if (res.code == 200) {
                self.$message({
                  message: '保存成功',
                  type: 'success'
                });
                self.$router.push({ path: '/management/Artcie' });
              } else if (res.code == 500) {
                self.$message.error('保存发生错误，请重新尝试');
              }
            })
            .catch(err => {
              self.$message.error('保存发生错误，请重新尝试');
            })
        }
      });
    },
    update () {
      var self = this;
      self.$refs.form.validate(valid => {
        if (valid) {
          if (self.form.coverUrl == null || self.form.coverUrl == '') {
            //获取editor中第一张图片的URL
            let reg = /<img.*?src="(.*?)"/;
            let match = this.form.content.match(reg);
            let firstImageUrl = match ? match[1] : '';
            self.form.coverUrl = firstImageUrl;
          }
          var text = this.editor.getText();
          var textEn = this.editorEn.getText();
          self.form.brief = text.length >= 100 ? this.editor.getText().substring(0, 100) : text;//中文只截取100个字
          self.form.briefEN = textEn.length >= 200 ? this.editorEn.getText().substring(0, 200) : textEn;//英文只截取200个字

          articleApi.updateArticle(self.form)
            .then(res => {
              if (res.code == 200) {
                self.$message({
                  message: '保存成功',
                  type: 'success'
                });
                self.$router.push({ path: '/management/Artcie' });
              } else if (res.code == 500) {
                self.$message.error('保存发生错误，请重新尝试');
              }
            })
            .catch(err => {
              self.$message.error('保存发生错误，请重新尝试');
            })
        }
      });
    },
    getArtcieById (id) {
      var self = this;
      articleApi.getArticleById(id)
        .then(res => {
          if (res.code == 200) {
            self.form = res.data;
            if (self.form.contentEn == null) {
              self.form.contentEn = "";
            }
          }
          else if (res.code == 500) {
            self.$message.error('编辑对象不存在，请检查参数');
            self.$router.push('/management/Artcie');
          }
        })
        .catch(err => {
          self.$message.error('接口出现错误');
        })
    },
    handleDelete () {
      // 删除文章
      var self = this;
      self.$confirm(`是否确定删除文章?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        articleApi.deleteArticleById(self.form.id)
          .then(res => {
            if (res.code == 200) {
              self.$message({
                message: '删除成功！',
                type: 'success'
              });
              self.$router.push({ path: '/management/Artcie' });
            }
            else if (res.code == 500) {
              self.$message.error('接口发生错误');
            }
          })
          .catch(err => {
            self.$message.error('接口发生错误');
          });
      });
    },
  },
  mounted () {
    var self = this;
    if (self.$route.query.id != null) {
      self.form.id = parseInt(self.$route.query.id);
      self.getArtcieById(self.form.id);
    }
  },
  beforeDestroy () {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
}
</script>

<style scoped>
.form {
  padding-top: 50px;
  position: relative;
}

.artcie-form-container {
  margin-bottom: 65px !important;
}

.form-set {
  display: flex;
}

.form-set-item label {
  margin-right: 10px;
}

.form-set-item+.form-set-item {
  margin-left: 20px;
}

.upload-box-img {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  width: 400px;
  height: 240px;
  margin-top: 20px;
  padding: 5px;
}

.upload-box-img img {
  width: 100%;
  height: 100%;
}

.cover-drawing {
  background-color: #f7f8fa;
  padding: 10px;
}

.cover-drawing .reminder {
  margin: 0px;
  color: #909399;
  margin-top: 5px;
  font-size: 14px;
}

.fix-buttons {
  /* background: #eee; */
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding-left: 200px;
}

.button-group {
  text-align: center;
  padding: 15px 0px;
  border-top: 1px solid #EBEEF5;
  background: #f7f8fa;
}

.button-group .el-button+.el-button {
  margin-left: 1px;
}
</style>